package cn.tedu.vrd.controller;

import cn.tedu.vrd.mapper.UserMapper;
import cn.tedu.vrd.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@RestController
public class UserController {

    @Autowired
    UserMapper mapper;

    @RequestMapping("/login")
    public int login(User user, String rem, HttpServletResponse response, HttpSession session){
        User u = mapper.selectByUsername(user.getUsername());
        if (u == null){
            return 2; //用户名不存在
        }
        if (u.getPassword().equals(user.getPassword())){
            //保存登录成功的用户对象
            session.setAttribute("u",u);
            if (rem != null){ //打勾了，需要记住用户名和密码
                //创建Cookie 保存用户名和密码
                Cookie c1 = new Cookie("username", user.getUsername());
                Cookie c2 = new Cookie("password", user.getPassword());
                response.addCookie(c1);
                response.addCookie(c2);
            }
            return 1; //登录成功
        }
        return 3; //密码错误
    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        return (User) session.getAttribute("u");
    }

    @RequestMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("u");
    }
}
